package com.interview.a_多线程.e_Thread和Object中的重要方.a_Wait_Notify;

/**
 * 展示  Wait 和 notify 基本用法
 * <p>
 * 研究代码的执行顺序
 * <p>
 * 证明 wait是 释放锁的
 */
public class WaitNotify {

    public static Object object = new Object();

    static class Thread1 extends Thread {
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + " 进入RUN方法 想要获取锁");
            synchronized (object) {
                System.out.println(Thread.currentThread().getName() + " 取锁成功");
                try {
                    System.out.println(Thread.currentThread().getName() + " 带着锁休息5秒... \n\n");
                    Thread.sleep(5000);
                    System.out.println("\n" + Thread.currentThread().getName() + " 休息完成 释放锁 并开始等待被唤醒\n\n");

                    object.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println(Thread.currentThread().getName() + " 被唤醒 并获取到了锁");
            }
        }
    }

    static class Thread2 extends Thread {
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + " 进入RUN方法 想要获取锁");
            synchronized (object) {
                object.notify();
                System.out.println(Thread.currentThread().getName() + "取锁成功，执行了唤醒notify（）");
            }
        }
    }


    public static void main(String[] args) throws InterruptedException {
        Thread1 thread1 = new Thread1();
        thread1.getState();
        thread1.start();
        thread1.setName("线程1");
        Thread.sleep(500);

        Thread2 thread2 = new Thread2();
        thread2.setName("线程2");
        thread2.start();

    }
}

